package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    //营业额数据统计
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //查询订单数据的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //封装日期对应的营业额数据
        List<Double> turnoverList = dateList.stream().map(x -> {
            LocalDateTime beginTime = LocalDateTime.of(x, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(x, LocalTime.MAX);
            Integer status = Orders.COMPLETED;
            Double result = orderMapper.subByStatusCount(beginTime, endTime, status);
            //营业额为0的情况
            result = result == null ? 0.0 : result;
            return result;

        }).collect(Collectors.toList());


        return TurnoverReportVO.builder().dateList(dateList.stream().map(LocalDate::toString).collect(Collectors.joining(","))).
                turnoverList(turnoverList.stream().map(String::valueOf).collect(Collectors.joining(","))).build();
    }

    //用户数据统计
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //查询用户数据的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //查询日期对应的用户总量
        List<Integer> totalUserList = new ArrayList<>();
        //查询日期对应的新用户数量
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end", endTime);
            //总用户数量
            Integer totalUser = userMapper.countByDate(map);
            //新用户数量
            map.put("begin", beginTime);
            Integer newUser = userMapper.countByDate(map);
            totalUserList.add(totalUser);
            newUserList.add(newUser);

        }


        return UserReportVO.builder().
                dateList(dateList.stream().map(LocalDate::toString).collect(Collectors.joining(","))).
                totalUserList(totalUserList.stream().map(String::valueOf).collect(Collectors.joining(","))).
                newUserList(newUserList.stream().map(String::valueOf).collect(Collectors.joining(","))).build();
    }

    //订单数据统计
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //查询用户数据的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //查询订单数据的日期
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //每日总订单数量
            Integer totalOrderCount = CountOrder(beginTime, endTime, null);
            //每日有效订单数量
            Integer validOrderCount = CountOrder(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(totalOrderCount);
            validOrderCountList.add(validOrderCount);
        }
        //订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }


        return OrderReportVO.builder()
                .dateList(dateList.stream().map(LocalDate::toString).collect(Collectors.joining(",")))
                .orderCountList(orderCountList.stream().map(String::valueOf).collect(Collectors.joining(",")))
                .validOrderCountList(validOrderCountList.stream().map(String::valueOf).collect(Collectors.joining(",")))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    //销量排名
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        //获取名称集合
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = String.join(",", names);
        //获取数量集合
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = numbers.stream().map(String::valueOf).collect(Collectors.joining(","));


        //封装返回结果
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    //导出数据
    @Override
    public void export(HttpServletResponse response) {
        //查询数据库 获取数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //通过poi 生成excel
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板创建excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充时间数据
            sheet.getRow(1).getCell(1).setCellValue("时间:" + begin + "~" + end);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());


            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO busyData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(busyData.getTurnover());
                row.getCell(3).setCellValue(busyData.getValidOrderCount());
                row.getCell(4).setCellValue(busyData.getOrderCompletionRate());
                row.getCell(6).setCellValue(busyData.getUnitPrice());
                row.getCell(5).setCellValue(busyData.getNewUsers());

            }


            //通过输出流 将excel写入到浏览器,完成下载
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);


            out.close();
            excel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //统计指定状态的订单数量(方法)
    private Integer CountOrder(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        Integer count = orderMapper.countByOrderStatus(map);
        return count == null ? 0 : count;
    }
}
